// 文件数据内容判断支持
let supports = {
	"mp3": ["494433"],
	"acc": ['FFF1', 'FFF9'],
	"wav": [['52494646', '57415645666D7420']],
	"gif": ["474946383961"],
	"png": ["89504E470D0A1A0A"],
	"jpeg": ["FFD8FFE000104A464946", "FFD8FFE1004C45786966"],
	"jpg": ["FFD8FFE000104A464946", "FFD8FFE1004C45786966"],
}

let fileFilter = {
	// 判断是否有权限
	isFileCanRead (file) {
		return new Promise(res => {
			file.arrayBuffer().then(r => {
				res({code: 1})
			}).catch(e => {
				if (e.name == 'NotReadableError') {
					res({code: 0, msg: '没有访问权限'})
				} else {
					res({code: 0, msg: '打开发生错误'})
				}
			})
		})
	},
	// 支持后缀格式判断
	checkFileSuffix (file, acceptSuffix) {
		// 是否有后缀名判断
		let index = file.name.lastIndexOf('.')
		if (index == -1) {
			return { code: 0, msg: "文件无后缀" }
		} 
		
		let suffix = file.name.substring(index + 1).toLowerCase()
		if (acceptSuffix) {
			if (!acceptSuffix.includes(suffix)) {
				return { code: 0, msg: "不支持该文件后缀"}
			}
		}
		
		return { code: 1, suffix }
	},
	// 检查文件后缀和真正格式是否相符合（防止篡改后缀）
	checkFileConform (file, targetSuffix) {
		return new Promise((res, rej) => {
			if (!targetSuffix) {
				res({code: 0, msg: "缺少要校验的后缀"})
				return 
			}
			
			let fileReader = new FileReader()
			
			fileReader.onload = function () {
				let result = new Uint8Array(this.result)
				let array = Array.from(result).map(function (element) {
					if (element.toString(16).length === 1) {
						return '0' + element.toString(16)
					} else {
						return element.toString(16)
					}
				})
				if (array.length) {
					let endData = array.join('')
					let status = []
					
					let support = supports[targetSuffix]
					
					support.forEach(item => {
						if (typeof item === 'object') {
							let itemData = []
							item.forEach((element, index) => {
								if (endData.indexOf(element.toLowerCase()) > -1) {
									itemData[index] = element
								}
							})
							if (itemData.length === item.length) {
								status = itemData
							}
						} else {
							if (endData.indexOf(item.toLowerCase()) > -1) {
								status[0] = item
							}
						}
					})
					
					if (status.length) {
						res({code: 1})
						return
					} else {
						res({code: 0, msg: `${targetSuffix}格式不符合`})
						return
					}
				} else {
					res({code: 0, msg: '检查发生错误'})
				}
			}
			fileReader.readAsArrayBuffer(file.slice(0, 16));
		})
	},
	// 检查文件是否可用
	async checkFile (file, acceptSuffix) {
		let res
		res = await this.isFileCanRead(file)
		if (!res.code) {
			return res
		}
		
		res = this.checkFileSuffix(file, acceptSuffix)
		if (!res.code) {
			return res
		}
		
		let suffix = res.suffix
		res = await this.checkFileConform(file, suffix)
		
		if (!res.code) {
			return res
		}
		
		return { ...res, suffix }
	}
}

export default fileFilter